<!-- 用户 -->
<template>
  <div class="all">
    <div class="serach">
      <el-card>
        <el-form :model="serachForm" inline class="form-inline">
          <el-form-item label="姓名">
            <el-input v-model="serachForm.name" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item style="margin-left: auto">
            <el-button round @click="loadTable">查询</el-button>
            <el-button round @click="dialogVisible = true">
              添加用户
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <div class="table">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column fixed prop="name" label="姓名" width="120" />
        <el-table-column prop="age" label="年龄" width="120" />
        <el-table-column prop="gender" label="性别" width="120" />
        <el-table-column prop="birth" label="出生日期" width="120" />
        <el-table-column prop="addr" label="地址" width="600" />
        <el-table-column fixed="right" label="Operations" min-width="120">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="prev, pager, next"
        :total="serachForm.total"
        @current-change="handleChange"
      />
    </div>
    <el-dialog
      v-model="dialogVisible"
      :title="editingUser.id ? '编辑用户' : '添加用户'"
      width="600px"
      status-icon
    >
      <el-form
        :model="editingUser"
        label-width="100px"
        :rules="rules"
        ref="userForm"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editingUser.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="editingUser.age" placeholder="请输入年龄" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="editingUser.gender" placeholder="请选择性别">
            <el-option :value="'男'" label="男" />
            <el-option :value="'女'" label="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期" prop="birth">
          <el-date-picker
            v-model="editingUser.birth"
            type="date"
            placeholder="出生日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="地址" prop="addr">
          <el-input v-model="editingUser.addr" placeholder="请输入地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUser">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<!--

  {
    prop: "name",
    label: "姓名",
  },
  {
    prop: "age",
    label: "年龄",
  },
  {
    prop: "sexLabel",
    label: "性别",
  },
  {
    prop: "birth",
    label: "出生日期",
    width: 200,
  },
  {
    prop: "addr",
    label: "地址",
    width: 400,
-->
<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { api } from "@/utils/api";

interface editingUserItem {
  id: number;
  name: string;
  age: number | null;
  gender: string;
  birth: string;
  addr: string;
}

const tableData = ref([]);
const serachForm = reactive({
  name: null,
  total: 0,
  page: 1,
});
const editingUser = reactive<editingUserItem>({
  id: 0,
  name: "",
  age: null,
  gender: "",
  birth: "",
  addr: "",
});
const NETWORK_ERR = ref("网络错误");
const dialogVisible = ref(false);
const rules = reactive({
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  age: [
    { required: true, message: "请输入年龄", trigger: "blur" },
    {
      validator: (
        rule: any,
        value: any,
        callback: (error?: string) => void
      ) => {
        if (value === null || value === undefined || isNaN(value)) {
          callback("年龄必须为数字");
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  gender: [{ required: true, message: "请选择性别", trigger: "change" }],
  birth: [{ required: true, message: "请选择出生日期", trigger: "change" }],
  addr: [{ required: true, message: "请输入地址", trigger: "blur" }],
});
const userForm = ref<InstanceType<typeof ElForm> | null>(null);
const loadTable = async () => {
  try {
    let response;
    if (serachForm.name != null || serachForm.page != 1) {
      let params = {
        name: serachForm.name || "",
        page: serachForm.page,
      };
      response = await api.get("/api/user/getTableData", params);
    } else {
      response = await api.get("/api/user/getTableData");
    }
    let { code, data, msg } = response;
    if (code == 200) {
      tableData.value = data.list;
      serachForm.total = data.count;
    } else {
      ElMessage.error(msg || NETWORK_ERR);
      return Promise.reject(msg || NETWORK_ERR);
    }
  } catch (error) {
    console.error("加载表格信息失败>", error);
    ElMessage.error("加载表格信息失败");
  }
};
const handleChange = (page: number) => {
  serachForm.page = page;
  loadTable();
};
const handleDelete = async (userId: number) => {
  try {
    await ElMessageBox.confirm("确定要删除这个用户吗？", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    // console.log('开始删除用户:', userId);
    await api.delete(`/api/user/delete/${userId}`);
    // console.log('删除用户响应:', response);

    ElMessage.success("删除成功");
    loadTable();
  } catch (error) {
    // console.error('删除用户时发生错误:', error);
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};
const dateFormat = (time: string) => {
  var temp = new Date(time);
  var year = temp.getFullYear();
  var month = temp.getMonth() + 1;
  var date = temp.getDate();
  function add(m: number) {
    return m < 10 ? "0" + m : m;
  }
  return year + "-" + add(month) + "-" + add(date);
};
const saveUser = async () => {
  try {
    if (!userForm.value) return;

    await userForm.value.validate((valid: boolean) => {
      if (valid) {
        editingUser.birth = dateFormat(editingUser.birth);
        const method = editingUser.id != 0 ? "put" : "post";
        api[method]("/api/user/save", editingUser)
          .then(() => {
            ElMessage.success("保存成功");
            dialogVisible.value = false;
            loadTable();
          })
          .catch((error) => {
            ElMessage.error("保存失败");
            console.error("保存用户时发生错误:", error);
          });
      } else {
        ElMessage.error("表单验证失败，请检查输入");
      }
    });
  } catch (error) {
    ElMessage.error("保存失败");
  }
};
const handleEdit = async (user: editingUserItem) => {
  Object.assign(editingUser, { ...user });
  dialogVisible.value = true;
};
onMounted(loadTable);
</script>

<style scoped lang="less">
.all {
  width: 100%;
  height: 100%;
}
.serach {
  margin-bottom: 20px;
}
.form-inline {
  display: flex;
  align-items: center;
  .el-form-item {
    width: 210px;
    margin-bottom: 0;
  }
}
.table {
  .er-table {
    width: 100%;
    height: 500px;
  }
  .el-pagination {
    margin-top: 20px;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
  }
}
</style>
